package com.ronghuanet.user.service.impl;

import com.ronghuanet.basic.util.AjaxResult;
import com.ronghuanet.basic.util.SmsUtil;
import com.ronghuanet.basic.util.StrUtils;
import com.ronghuanet.basic.util.VerifyCodeUtils;
import com.ronghuanet.car.service.ICarDetailService;
import com.ronghuanet.user.domain.Logininfo;
import com.ronghuanet.user.dto.SmsCodeDto;
import com.ronghuanet.user.mapper.LogininfoMapper;
import com.ronghuanet.user.service.IVerifyCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${sms.code.register.resend-time}")
    private Integer resendTime;
    @Value("${sms.code.register.expire-time}")
    private Integer expireTime;

    @Override
    public String getImageCode(String key) throws IOException {
        //生成4为验证码
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //验证吗放入redis，并且3分钟过期时间
        redisTemplate.opsForValue().set("imgVerifyCode_"+key,verifyCode,3, TimeUnit.MINUTES);
        //把验证码合成图片并加密为base64数据进行返回
        String base64Data = VerifyCodeUtils.VerifyCode(100,40,verifyCode);
        return base64Data;
    }


    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    public AjaxResult sendSmsCodeRegister(SmsCodeDto smsCodeDto) {
        String mobile = smsCodeDto.getMobile();
        String imageCodekey = smsCodeDto.getImageCodeKey();
        String imageCode = smsCodeDto.getImageCode();
        //1 校验
        //1.0 空判断
        if (StringUtils.isEmpty(mobile)||StringUtils.isEmpty(imageCodekey)||StringUtils.isEmpty(imageCode))
            return AjaxResult.me().setSuccess(false).setMessage("非法请求，参数异常！");
        //1.1 判断图片验证码是否正确
        String imageCodeOfRedis = (String) redisTemplate.opsForValue()
                .get("imgVerifyCode_"+imageCodekey);
        if (!imageCode.trim().equalsIgnoreCase(imageCodeOfRedis))
            return AjaxResult.me().setSuccess(false).setMessage("请输入正确图片验证码！");
        //1.2 判断手机号是否已经被注册
        Logininfo logininfo = logininfoMapper.loadUserByMobile(mobile);
        if(logininfo!=null)
            return AjaxResult.me().setSuccess(false).setMessage("该手机号已经被注册！请登录后使用！");

        //2 判断原来的验证码是否存在
        String key ="register_sms_code_" + mobile;

        String smsCodeOfRedis = (String) redisTemplate.opsForValue()
                .get(key);
        String code = "";
        if (StringUtils.isEmpty(smsCodeOfRedis)) {
            //2.1 如果不存在就产生新的
            code = StrUtils.getRandomString(6);
        }else{
            //2.2 如果存在，判断是否已过重发时间，如果没有过报错，过了直接原来的
            code = smsCodeOfRedis.split(":")[0];              //code:time
            String time = smsCodeOfRedis.split(":")[1];              //code:time
            if (System.currentTimeMillis()-new Date(Long.valueOf(time)).getTime() <= 60*1000*resendTime)  //60*1000
            {
                return AjaxResult.me().setSuccess(false).setMessage("非法请求，请勿乱搞！");
            }
        }


        //3 记录验证码到redis
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),expireTime, TimeUnit.MINUTES);


        //4 调用短信接口进行发送
        String content = String.format("你的验证码为%s,请在%s分钟之内使用！", code, expireTime);
        //SmsUtil.sendSms(mobile,content);
        System.out.println("已经成功发送了一条短信,内容为"+content);

        //5 记录发送记录 @TODO

        return AjaxResult.me();
    }
}
